import { createRouter, createWebHashHistory, RouteLocationNormalized, RouteRecordRaw } from 'vue-router'
import { store } from '@/store'
import axios from 'axios'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { userInit } from '@/api/mapData'
const routes: RouteRecordRaw[] = [

  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/home/index.vue'),
    meta: { title: '首页' }
  },
  {
    path: '/modules/zdryTjxx',
    name: 'zdryTjxx',
    component: () => import('@/views/modules/zdryTjxx.vue'),
    meta: { title: '重点人员统计信息' }
  },
  {
    path: '/modules/jczZgxx',
    name: 'jczZgxx',
    component: () => import('@/views/modules/jczZgxx.vue'),
    meta: { title: '检查站战果统计' }
  },
  {
    path: '/configScreen',
    name: 'configScreen',
    component: () => import('@/views/system/configScreen.vue'),
    meta: { title: '大屏配置' }
  },
  {
    path: '/controlFocus',
    name: 'controlFocus',
    component: () => import('@/views/controlFocus/unifiedControl.vue'),
    meta: { title: '统一布控' }
  },
  {
    path: '/toSearch',
    name: 'toSearch',
    component: () => import('@/views/search/toSearch.vue'),
    meta: { title: '统一查询' }
  },
  {
    path: '/mapApp',
    name: 'mapApp',
    component: () => import('@/components/MapApp/MainMap.vue'),
    meta: { title: '地图应用' }
  },
  {
    path: '/dialog',
    name: 'dialog',
    component: () => import('@/views/test/dialog.vue'),
    meta: { title: '弹窗测试' }
  },
  {
    path: '/mapConfig',
    name: 'mapConfig',
    component: () => import('@/views/mapConfig/index.vue'),
    meta: { title: '地图应用配置' }
  },
  {
    path: '/mapHome',
    name: 'mapHome',
    component: () => import('@/views/home/mapHome.vue'),
    meta: { title: '地图应用' }
  }
]
const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 路由守卫
router.beforeEach(async () => {
  NProgress.start()
  // 获取配置信息
  if (JSON.stringify(store.state.config) === '{}') {
    const config = await axios.get(`${import.meta.env.BASE_URL}apiHost.json`)
    store.commit('setConfig', config.data)
  }
  const token = getToken()
  console.log('token' + token)
  if (token) {
    if (JSON.stringify(store.state.dictionary) === '{}') {
      await store.dispatch('setDictionarySync')
    }
    await userInit()
  }

  NProgress.done()
})

router.afterEach((to: RouteLocationNormalized) => {
  document.title = `${store.state.config.appName}-${to.meta.title}`
})

export default router
